/**
 *@NApiVersion 2.x
 *@NScriptType Suitelet
 */
define(['N/ui/serverWidget', 'N/record', 'N/search'], function (ui, record, search) {
    function onRequest(context) {

        var response = {};
        var param = JSON.parse(context.request.parameters.param);
        switch (param.type) {
            case 'transferorder':
                var results = createTransferOrders(param);
                var messages = [];
                for (var i = 0; i < results.length; i++) {
                    var message = {};
                    if (results[i].success) {
                        var toid = results[i].id;
                        var toRec = record.load({type: 'transferorder', id: toid, isDynamic: true});
                        var totranid = toRec.getText('tranid');
                        message.msg = results[i].fromLocation + ' 创建调拨单 ' + totranid + ' 成功! ';
                        message.id = toid;
                        message.type = param.type;
                        message.success = results[i].success;
                    } else {
                        message.msg = results[i].fromLocation + ' 创建调拨单失败';
                        message.success = results[i].success;
                        message.error = results[i].error;
                    }
                    messages.push(message);
                }
                response.messages = messages;
                break;
            case 'inventorytransfer':
                var results = createInventoryTransfer(param);
                var messages = [];
                for (var i = 0; i < results.length; i++) {
                    var message = {};
                    if (results[i].success) {
                        var itid = results[i].id;
                        var itRec = record.load({type: 'inventorytransfer', id: itid, isDynamic: true});
                        var ittranid = itRec.getText('tranid');
                        message.msg = results[i].fromLocation + ' 创建库存转移单 ' + ittranid + ' 成功! ';
                        message.id = itid;
                        message.type = param.type;
                        message.success = results[i].success;
                    } else {
                        message.msg = results[i].fromLocation + ' 创建库存转移单失败';
                        message.success = results[i].success;
                        message.error = results[i].error;
                    }
                    messages.push(message);
                }
                response.messages = messages;
                break;
            default :
                response.messages = [{'msg': ' 创建失败'}];
                break;
        }
        context.response.write(JSON.stringify(response));//返回到response body里面
    }


    function createTransferOrders(param) {
        var results = [];
        for (var i = 0; i < param.fromLocations.length; i++) {
            try {
                var rec = record.create({type: 'transferorder', isDynamic: true});
                rec.setValue('subsidiary', param.subsidiary);
                // rec.setText('orderstatus', param.orderstatus);
                var fromLocation = param.fromLocations[i];
                rec.setValue('location', fromLocation);
                rec.setValue('transferlocation', param.toLocation);
                rec.setValue('custbody_relatedtransation', param.related);
                var fromLocationName;
                for (var j = 0; j < param.items.length; j++) {
                    if (param.items[j].fromLocation == fromLocation) {
                        fromLocationName = param.items[j].fromLocationName;
                        rec.selectNewLine('item');
                        rec.setCurrentSublistValue('item', 'item', param.items[j].itemId);
                        rec.setCurrentSublistValue('item', 'quantity', param.items[j].quantity);
                        rec.setCurrentSublistValue('item', 'rate', param.items[j].rate);
                        rec.setCurrentSublistValue('item', 'custcol_outsource_location', param.items[j].custcol_outsource_location);
                        rec.setCurrentSublistValue('item', 'custcol_outsource_bin', param.items[j].custcol_outsource_bin);
                        rec.setCurrentSublistValue('item', 'custcol_outsourcelocationavailableqty', param.items[j].custcol_outsourcelocationavailableqty);
                        rec.commitLine('item');
                    }
                }
                var toid = rec.save();

                var result = {};
                result.id = toid;
                result.success = true;
                result.fromLocation = fromLocationName;
            } catch (e) {
                log.debug('create  record  error', JSON.stringify(e));
                var result = {};
                result.id = '';
                result.success = false;
                result.fromLocation = fromLocationName;
                result.error = JSON.stringify(e);
            }
            results.push(result);
        }
        return results;
    }

    function createInventoryTransfer(param) {
        var results = [];
        for (var i = 0; i < param.fromLocations.length; i++) {
            try {
                var rec = record.create({type: 'inventorytransfer', isDynamic: true});
                rec.setValue('subsidiary', param.subsidiary);

                var fromLocation = param.fromLocations[i];
                rec.setValue('location', fromLocation);

                rec.setValue('transferlocation', param.toLocation);
                rec.setValue('custbody_relatedtransation', param.related);
                var fromLocationName;
                for (var j = 0; j < param.items.length; j++) {
                    if (param.items[j].fromLocation.toString() === fromLocation.toString()) {
                        fromLocationName = param.items[j].fromLocationName;
                        rec.selectNewLine('inventory');
                        rec.setCurrentSublistValue('inventory', 'item', param.items[j].itemId);
                        rec.setCurrentSublistValue('inventory', 'adjustqtyby', param.items[j].quantity);
                        var inventoryDetailRec = rec.getCurrentSublistSubrecord('inventory', 'inventorydetail');
                        inventoryDetailRec.selectNewLine('inventoryassignment');
                        if (param.items[i].fromBin) {
                            inventoryDetailRec.setCurrentSublistValue('inventoryassignment', 'binnumber', param.items[j].fromBin);
                        }
                        inventoryDetailRec.setCurrentSublistValue('inventoryassignment', 'tobinnumber', param.items[j].toBin);
                        inventoryDetailRec.setCurrentSublistValue('inventoryassignment', 'quantity', param.items[j].quantity);
                        inventoryDetailRec.commitLine('inventoryassignment');
                        rec.commitLine('inventory');
                    }
                }
                var itid = rec.save();

                var result = {};
                result.id = itid;
                result.success = true;
                result.fromLocation = fromLocationName;
            } catch (e) {
                var result = {};
                result.id = '';
                result.success = false;
                result.fromLocation = fromLocationName;
                result.error = JSON.stringify(e);
            }
            results.push(result);
        }
        return results;
    }

    return {
        onRequest: onRequest
    };
});